﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using WHO_Auth_TNG_Win;

namespace WHT_Auth {
    public partial class StartOptions : Form {
        public StartOptions() {
            InitializeComponent();
        }

        private MainWindow mainWindow;
        
        public StartOptions(MainWindow mainWindow) {
            InitializeComponent();
            this.mainWindow = mainWindow;
            textUsername.Focus();
        }

        private void buttonOk_Click(object sender, EventArgs e) {
            if (verifyInput() || (!verifyInput() && MessageBox.Show(this, "The user name you provided may not be correct. Do you want to to continue anyway?", "Username invalid", MessageBoxButtons.YesNo) == DialogResult.Yes)) {

                bool credentialsChanged = (WHT_Auth.Properties.Settings.Default.username != textUsername.Text || mainWindow.auth.password != textPassword.Text);

                WHT_Auth.Properties.Settings.Default.username = textUsername.Text;
                WHT_Auth.Properties.Settings.Default.savePassword = true;
                WHT_Auth.Properties.Settings.Default.startMinmized = true;
                WHT_Auth.Properties.Settings.Default.quitAction = 1;

                //Password
                    WHT_Auth.Properties.Settings.Default.password = Base64.Encode(textPassword.Text);


                //Autostart
                string keyName = "WHO-Auth TNG";
                string assemblyLocation = Application.ExecutablePath;
                AutoStart.SetAutoStart(keyName, assemblyLocation);


                mainWindow.auth.password = textPassword.Text;
                WHT_Auth.Properties.Settings.Default.Save();
                
                    //Check connection and use credentials if needed
                    mainWindow.auth.initialize();
                
                this.Close();
            }

            

        }

        private void buttonCancel_Click(object sender, EventArgs e) {
                //Dirty but it works. Look for nicer solution
                Application.Exit();
        }

        private bool verifyInput() {
            Regex exp = new Regex(@"[a-z]{5}[0-9]{2}", RegexOptions.IgnoreCase);
            MatchCollection MatchList = exp.Matches(textUsername.Text);
            if (MatchList.Count < 1)
                return false;
            else
                return true;

        }

        private void textPassword_KeyPress(object sender, KeyPressEventArgs e) {
            if (e.KeyChar == '\r') {
                buttonOk_Click(sender, null);
            }
        }

    }
}
